package utils

import (
	"errors"
	"time"

	"backend-api/config"

	"github.com/golang-jwt/jwt/v5"
)

// JWTClaims JWT声明结构
type JWTClaims struct {
	UserID   uint   `json:"user_id"`
	UUID     string `json:"uuid"`
	Username string `json:"username"`
	UserType string `json:"user_type"` // "user" 或 "admin"
	jwt.RegisteredClaims
}

// GenerateFrontendToken 生成前台用户JWT令牌
func GenerateFrontendToken(userID uint, uuid, username string) (string, error) {
	cfg := config.GlobalConfig.JWT.Frontend

	claims := JWTClaims{
		UserID:   userID,
		UUID:     uuid,
		Username: username,
		UserType: "user",
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    cfg.Issuer,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(cfg.ExpireTime) * time.Second)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(cfg.Secret))
}

// GenerateAdminToken 生成后台管理员JWT令牌
func GenerateAdminToken(adminID uint, uuid, username string) (string, error) {
	cfg := config.GlobalConfig.JWT.Admin

	claims := JWTClaims{
		UserID:   adminID,
		UUID:     uuid,
		Username: username,
		UserType: "admin",
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    cfg.Issuer,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(cfg.ExpireTime) * time.Second)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(cfg.Secret))
}

// ParseFrontendToken 解析前台用户JWT令牌
func ParseFrontendToken(tokenString string) (*JWTClaims, error) {
	cfg := config.GlobalConfig.JWT.Frontend

	token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(cfg.Secret), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
		// 验证用户类型
		if claims.UserType != "user" {
			return nil, errors.New("无效的用户类型")
		}
		return claims, nil
	}

	return nil, errors.New("无效的令牌")
}

// ParseAdminToken 解析后台管理员JWT令牌
func ParseAdminToken(tokenString string) (*JWTClaims, error) {
	cfg := config.GlobalConfig.JWT.Admin

	token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(cfg.Secret), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
		// 验证用户类型
		if claims.UserType != "admin" {
			return nil, errors.New("无效的用户类型")
		}
		return claims, nil
	}

	return nil, errors.New("无效的令牌")
}